package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.system.SystemUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hitqz.robot.api.business.dto.PatrolResultDto;
import com.hitqz.robot.api.business.entity.PatrolResultEntity;
import com.hitqz.robot.api.business.params.QueryPatrolDetailNewParams;
import com.hitqz.robot.api.business.params.QueryPatrolSummaryNewParams;
import com.hitqz.robot.api.business.params.QueryPatrolSummaryParams;
import com.hitqz.robot.api.business.vo.PatrolResultNewVo;
import com.hitqz.robot.api.business.vo.PatrolResultSummaryNewVo;
import com.hitqz.robot.api.business.vo.PatrolResultSummaryVo;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotConfig;
import com.hitqz.robot.api.common.entity.Tickets;
import com.hitqz.robot.biz.core.FileProperties;
import com.hitqz.robot.biz.mapper.PatrolResultMapper;
import com.hitqz.robot.biz.service.PatrolResultService;
import com.hitqz.robot.biz.service.RobotConfigService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.biz.service.TicketsService;
import com.hitqz.robot.biz.util.PatrolConstant;
import com.hitqz.robot.common.core.constant.CommonConstants;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.netty.service.Send2ServerService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.Map;
import java.util.Objects;

/**
 * @author wengyx
 * @date 2024/8/7
 */
@Service
@AllArgsConstructor
@Slf4j
public class PatroResultServiceIml extends ServiceImpl<PatrolResultMapper, PatrolResultEntity> implements PatrolResultService {

    private final RobotService robotService;

    private final FileProperties fileProperties;
    private final RestTemplate restTemplate;

    private final Send2ServerService send2ServerService;

    private final RobotConfigService robotConfigService;

    private final TicketsService ticketsService;


    @Override
    public Page<PatrolResultSummaryVo> summaryPage(Page<PatrolResultSummaryVo> page, QueryPatrolSummaryParams query) {
        return baseMapper.summaryPage(page,query);
    }


    @Override
    public PatrolResultSummaryVo summary(QueryPatrolSummaryParams query) {
        return baseMapper.summary(query);
    }

    @Override
    public void upload2Server(PatrolResultEntity patrolResultEntity) {
        try {
            Robot robot = robotService.getDefaultRobot();
            RobotConfig config = robotConfigService.getOneEnable();
            Tickets clientTickets = ticketsService.getById(patrolResultEntity.getTicketsId());
            if (clientTickets == null || clientTickets.getServerId()==null){
                return;
            }
            PatrolResultDto patrolResultDto = BeanUtil.copyProperties(patrolResultEntity, PatrolResultDto.class);
            patrolResultDto.setTicketsId(clientTickets.getServerId());
            String mediaUrl = patrolResultEntity.getMediaUrl();
            if (StrUtil.isNotBlank(mediaUrl)) {
                if (SystemUtil.getOsInfo().isWindows()){
                    mediaUrl = mediaUrl.replace("\\","/");
                }
                patrolResultDto.setMediaUrl(config.getProcessManagerUri() + "/file" + URLUtil.encode(mediaUrl));
            }else {
                patrolResultDto.setMediaUrl(null);
            }
            String visionMediaUrl = patrolResultEntity.getVisionMediaUrl();
            if (StrUtil.isNotBlank(visionMediaUrl)) {
                if (SystemUtil.getOsInfo().isWindows()){
                    visionMediaUrl = visionMediaUrl.replace("\\","/");
                }
                patrolResultDto.setVisionMediaUrl(config.getProcessManagerUri() + "/file" + URLUtil.encode(visionMediaUrl));
            }else {
                patrolResultDto.setVisionMediaUrl(null);
            }
            if (!Objects.equals(patrolResultDto.getStatus(),0)){
                PatrolConstant.patrolTaskDto = patrolResultDto;
            }
            send2ServerService.sendPatrolResult(robot,patrolResultDto);
            //serverDao.uploadDir();
        }catch (Exception e) {

        }

    }

    private String uploadImage(String path) {
        String uploadPath = "";
        try {
            File file = new File(fileProperties.getLocal().getBasePath() + path);
            FileSystemResource resource = new FileSystemResource(file);
            Robot robot = robotService.getDefaultRobot();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", resource);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            R result = restTemplate.postForObject("http://" + robot.getServerAddress() + ":9999/admin/sys-file/uploadDir",
                    requestEntity, R.class);
            if (result.getCode() ==  CommonConstants.SUCCESS.intValue()) {
                Map<String, Object> data = (Map<String, Object>) result.getData();
                uploadPath = String.valueOf(data.get("url"));
            }
            log.info("工单结果上传文件" + uploadPath);
        } catch (Exception e) {
            System.err.println("Error uploading image: " + e.getMessage());
        }
        return uploadPath;
    }

}
